﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using EarthWatchers.SL.Requests;
using Earthwatchers.Models;
using SharpMap;
using EarthWatchers.SL.Layers;
using EarthWatchers.SL.GUI.Controls;
using System.Windows.Browser;
using System.Collections.Generic;

namespace EarthWatchers.SL
{
    public partial class MainPage
    {
        private LayerHelper layerHelper;
        private HexagonInfo hexagonInfo;
        private bool leftMouseButtonDown;
        private bool loaded;
        private bool rightMenuOpen;
        private DispatcherTimer timer;

        public MainPage()
        {
            InitializeComponent();
            Loaded += MainPageLoaded;
            
            Current.Instance.Main = this; //TODO: remove after demo
            userInfo.UserLoggedIn += UserLoggedIn;
            userInfo.UserLoggedOut += UserLoggedOut;
        }

        private void UserLoggedOut(object sender, System.EventArgs e)
        {
            dragCanvas.Visibility = Visibility.Collapsed;
            menuGrid.Height = 138;
        }

        private void UserLoggedIn(object sender, System.EventArgs e)
        {
            dragCanvas.Visibility = Visibility.Visible;
            menuGrid.Height = 163;
        }

        private void MainPageLoaded(object sender, RoutedEventArgs e)
        {
            //Create and set map
            var map = new Map();
            mapControl.Map = map;

            //Initialize the singleton
            Current.Instance.MapControl = mapControl;

            //Pass the LayerCollection used on the map to the helper, this is used to distinguish base, normal, ... layers 
            layerHelper = new LayerHelper(map.Layers);
            Current.Instance.LayerHelper = layerHelper;
            layerList.SetLayerHelper(layerHelper);

            //Load the preset layers
            LayerInitialization.Initialize(layerHelper);

            hexagonInfo = new HexagonInfo();
            landInfoWrapper.Children.Add(hexagonInfo);

            userInfo.TryGetUserInfo();
            StartTimer(null, null);
        }

        public void SetLegendGraphic(BitmapImage image)
        {
            legendGrid.Visibility = Visibility.Visible;
            legendImage.Source = image;
        }

        public void StartTimer(object o, RoutedEventArgs sender)
        {
            timer = new DispatcherTimer {Interval = new TimeSpan(0, 0, 0, 1, 0)};
            timer.Tick += InitHack;
            timer.Start();
        }

        // Hack, map has no initialised event so delay reading of send params
        public void InitHack(object o, EventArgs sender)
        {
            if (!loaded)
            {
                loaded = !loaded;
                timer.Stop();
                try
                {
                    PermalinkHelper.GetPermalinkromUrl();
                    var referedGeoHex = HtmlPage.Document.QueryString["hexkey"];
                    MapHelper.ZoomToHexagon(mapControl, referedGeoHex);
                }
                catch (KeyNotFoundException) { }
            }
        }

        /*
         * The map is shown in the middle of the screen, since Silverlight is unable to clipToBounds
         * the grid needs Clip, the rect has to change when the window is resized.
         */
        #region button handlers

        private void BtnFullscreenMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Application.Current.Host.Content.IsFullScreen = !Application.Current.Host.Content.IsFullScreen;
        }

        private void BtnHelpMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var helpWindow = new HelpWindow();
            helpWindow.Show();
        }

        #endregion

        #region mouse events

        private void MapControlMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            leftMouseButtonDown = true;

            if (!layerHelper.FindLayer(Constants.Hexagonlayername).Enabled) 
                return;

            var mousePos = e.GetPosition(mapControl);
            var sphericalCoordinate = mapControl.View.ViewToWorld(mousePos.X, mousePos.Y);
            var lonLat = SphericalMercator.ToLonLat(sphericalCoordinate.X, sphericalCoordinate.Y);
            hexagonInfo.ShowInfo(lonLat.x, lonLat.y);
        }

        private void MapControlMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            leftMouseButtonDown = false;            
        }

        private void MapControlMouseLeave(object sender, MouseEventArgs e)
        {
            leftMouseButtonDown = true;
        }

        private void MapControlMouseMove(object sender, MouseEventArgs e)
        {
            if (!leftMouseButtonDown)
                return;

            hexagonInfo.Move();
        }

        #endregion

        private void BtnZoomInClick(object sender, RoutedEventArgs e)
        {
            mapControl.ZoomIn();
        }

        private void BtnZoomOutClick(object sender, RoutedEventArgs e)
        {
            mapControl.ZoomOut();
        }

        private void BtnLeftMenuMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!rightMenuOpen)
                OpenRightMenu.Begin();
            else            
                CloseRightMenu.Begin();

            rightMenuOpen = !rightMenuOpen;
        }

        private void BtnLeftMenuMouseEnter(object sender, MouseEventArgs e)
        {
            txtInfo.Foreground = new SolidColorBrush(Color.FromArgb(255, 159, 181, 11));
        }

        private void BtnLeftMenuMouseLeave(object sender, MouseEventArgs e)
        {
            txtInfo.Foreground = new SolidColorBrush(Colors.Black);
        }

        private void PublishClick(object sender, MouseButtonEventArgs e)
        {
            var pb = new PublishMap();
            pb.Show();
        }

        private void DistanceClick(object sender, MouseButtonEventArgs e)
        {
            distanceCalculator.Visibility = Visibility.Visible;
        }
        List<String> adresses_list = new List<string>();
        private void callbackSuggestion(List<String> suggestions)
        {
            if (suggestions != null)
            {
                var i = 0;

                adresses_list = suggestions;
            }

        }
        string address = " ";
       
        private void onText_Changed(object sender, EventArgs e)
    {
        address = txt_search.Text;
        List<string> suggested_addresses = new List<string>();
        OpengeocoderRequests.GetSuggestions(callbackSuggestion, address);
        combo_search.ItemsSource = adresses_list;
        address = combo_search.SelectedItem.ToString();

            }
        
    
        private void on_Selection_changed(object sender, SelectionChangedEventArgs e)
        
    {
                 txt_search.Text = combo_search.SelectedValue.ToString();
           
        }
        private void on_CheckBox_Checked(object sender, EventArgs e)
        {
            txt_search.Visibility = Visibility.Visible;
            combo_search.Visibility = Visibility.Visible;
               
        }
        private void on_CheckBox_UnChecked(object sender, EventArgs e)
        {
            txt_search.Text = "";
            txt_search.Visibility = Visibility.Collapsed;
            combo_search.Visibility = Visibility.Collapsed;

        }
        private void SearchClick(object sender, MouseButtonEventArgs e)
        {
           
            OpengeocoderRequests.GetQueryResult(callback,address );
  
        }

        private void callback(QueryResult queryResult)
        {
            if (queryResult != null)
            {
                var xyStart = SphericalMercator.FromLonLat(queryResult.bbox[0], queryResult.bbox[1]);
                var xyEnd = SphericalMercator.FromLonLat(queryResult.bbox[2], queryResult.bbox[3]);

                var beginPoint = new SharpMap.Geometries.Point(xyStart.x, xyStart.y);
                var endPoint = new SharpMap.Geometries.Point(xyEnd.x, xyEnd.y);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                    mapControl.ZoomToBox(beginPoint, endPoint)
                );
            }
        }
    }
}
